package utils

import (
	"Junior_two/subject/cart/cartrpc/model"
	"Junior_two/subject/common"
	"context"
	"encoding/json"
	"fmt"
	"strconv"
)

var redisClient = common.RedisClient()

func RedisLPush(key string) bool {
	_, err := redisClient.LPush(context.Background(), key, 1).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func RedisLLen(key string) (int64, bool) {
	size, err := redisClient.LLen(context.Background(), key).Result()
	if err != nil {
		fmt.Println(err)
		return 0, false
	}
	return size, true
}

func RedisHSet(key string, value model.Cart, goodId int64) bool {
	JsV, _ := json.Marshal(value)
	_, err := redisClient.HSet(context.Background(), key, map[string]interface{}{strconv.Itoa(int(goodId)): JsV}).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func RedisLPop(key string) bool {
	_, err := redisClient.LPop(context.Background(), key).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func RedisHex(key string, goodId int64) bool {
	return redisClient.HExists(context.Background(), key, strconv.Itoa(int(goodId))).Val()
}

func RedisHGet(key string, goodId int64) model.Cart {
	str, err := redisClient.HGet(context.Background(), key, strconv.Itoa(int(goodId))).Result()
	if err != nil {
		fmt.Println(err)
		return model.Cart{}
	}
	var c model.Cart
	json.Unmarshal([]byte(str), &c)
	return c
}

func RedisDel(key string, goodId int64) bool {
	_, err := redisClient.HDel(context.Background(), key, strconv.Itoa(int(goodId))).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}
